﻿namespace Guia.Elements
{
    using System;
    using System.Diagnostics.Contracts;
    using System.Windows.Automation;
    using Guia.Config;
    using Guia.Locator;

    /// <summary>
    /// This class represents a (WinForms) OpenFileDialog.
    /// </summary>
    public class OpenFileDialog : UiElement
    {
        /// <summary>
        /// Initializes a new instance of the OpenFileDialog class. 
        /// </summary>
        /// <param name="automationElement">The AutomationElement representating the OpenFileDialog.</param>
        public OpenFileDialog(AutomationElement automationElement)
            : base(automationElement)
        {
        }

        /// <summary>
        /// Gets the default-condition to find a control by its type.
        /// </summary>
        public static SearchCondition ControlTypeCondition
        {
            get { return SearchCondition.ByControlType(ControlType.Window).And(SearchCondition.ByClassName("#32770")); }
        }

        /// <summary>
        /// Sets the FilePath. 
        /// </summary>
        private string FilePath
        {
            set
            {
                ComboBox comboBox = this.Get<ComboBox>("1148");
                TextBox textBox = comboBox.Get<TextBox>("1148");
                textBox.Value = value;
            }
        }

        /// <summary>
        /// Opens the given file.
        /// </summary>
        /// <param name="filePath">The path of the desired file.</param>
        /// <exception cref="ArgumentNullException">This exception is thrown if filePath is null.</exception>
        public void Open(string filePath)
        {
            Contract.Requires<ArgumentNullException>(filePath != null);
            this.Open(new string[] { filePath });
        }

        /// <summary>
        /// Opens the given files.
        /// </summary>
        /// <param name="filePaths">The files to open.</param>
        /// <exception cref="ArgumentNullException">This exception is thrown if filePaths is null.</exception>
        public void Open(string[] filePaths)
        {
            Contract.Requires<ArgumentNullException>(filePaths != null);
            string wholeFilePath = string.Empty;
            foreach (string s in filePaths)
            {
                wholeFilePath += "\"" + s + "\" ";
            }

            wholeFilePath = wholeFilePath.Trim();
            this.FilePath = wholeFilePath;
            this.Open();
        }

        /// <summary>
        /// Cancels the dialog.
        /// </summary>
        public void Cancel()
        {
            this.Get<Button>("2").Invoke();
        }

        /// <summary>
        /// Opens the given file.
        /// </summary>
        private void Open()
        {
            this.Get<Button>("1").Invoke();
        }
    }
}
